import React, { useEffect, useState, useMemo, useContext } from "react";
import { Button, Card, Form, Input, Space, message } from "antd";
import PromptBox from "../../components/ValidateBox/ProtoBox";
import { setIcon } from "../../utils/setIcon";
import Context from "./context";
// import { drawVerfiCode } from "../../utils/canvasDraw";
import axios from "axios";
import moment from "moment";
export default function LoginForm() {
  const [form] = Form.useForm();
  // const [errorWord,setErrorWord] = useState(['','','']) // 本想写成这样子 但是发现和不自定义校验一样 不能在表单change事件的实时同步help框 而且不写form,直接提交 不会显示提示文案 antd对数组不太敏感
  const [nameerrorWord, setNameErrorWord] = useState(undefined);
  const [passworderrorWord, setPasswordErrorWord] = useState(undefined);
  const [isPassworderrWord, setisPasswordErrorWord] = useState(undefined);
  const [focusItem, setfocusItem] = useState(0);
  const { ele } = { ...useContext(Context) };
  const nameicon = useMemo(() => {
    return setIcon(focusItem, nameerrorWord, 1);
  }, [focusItem, nameerrorWord]);
  const passwordicon = useMemo(() => {
    return setIcon(focusItem, passworderrorWord);
  }, [focusItem, passworderrorWord]);
  const isPasswordicon = useMemo(() => {
    return setIcon(focusItem, isPassworderrWord);
  }, [focusItem, isPassworderrWord]);
  const onFinish = (value) => {
    console.log(value);
  };
  const submit = () => {
    setfocusItem(0);
    form
      .validateFields()
      .then(async (values) => {
        let { data: res } = await axios.post("register", {
          username: values.username,
          password: values.password,
          registeraddress: window.secretip,
          registertime: moment().format("X"),
        });
        if (res.ok === -1) {
          return message.error("注册失败");
        } else if (res.ok === 0) {
          return setNameErrorWord((prev) => res.message);
        }
        message.success(res.message);
        setTimeout(()=>{
          toLogin()
        },500)
        // let res = await axios.get('https://api.ipify.org/?format=jsonp&callback=?') ;
        // console.log(res) ;
      })
      .catch((errorInfo) => {
        // setErrorWord(form.getFieldError('username')[0])
        // console.log(errorWord);
        // console.log(errorInfo);
      });
  };
  // 自定义校验为的是数据表单数据一点改变 就会在改变时提示 不是只在失去焦点时提示
  const checkName = (rule, value, callback) => {
    return new Promise(async (reslove, reject) => {
      if (!value) {
        setNameErrorWord((prev) => "用户名不能为空");
        reject(new Error("用户名不能为空"));
      } else {
        if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(value)) {
          setNameErrorWord((prev) => "不能有特殊的字符");
          reject(new Error("不能有特殊的字符"));
        } else {
          setNameErrorWord((prev) => "");
          reslove();
        }
      }
    });
  };
  const checkPassword = (rule, value, callback) => {
    return new Promise(async (reslove, reject) => {
      if (!value) {
        setPasswordErrorWord((prev) => "密码不能为空");
        reject(new Error("密码不能为空"));
      } else {
        if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(value)) {
          setPasswordErrorWord((prev) => "不能有特殊的字符");
          reject(new Error("不能有特殊的字符"));
        } else {
          setPasswordErrorWord((prev) => "");
          reslove();
        }
      }
    });
  };
  const checkisPassword = (rule, value, callback) => {
    return new Promise(async (reslove, reject) => {
      if (!value) {
        setisPasswordErrorWord((prev) => "必须确认密码");
        reject(new Error("确认密码不能为空"));
      } else {
        if (value !== form.getFieldValue("password")) {
          setisPasswordErrorWord((prev) => "2次密码不一致");
          reject(new Error("2次密码不一致"));
        } else {
          setisPasswordErrorWord((prev) => "");
          reslove();
        }
      }
    });
  };
  const toLogin = () => {
    setNameErrorWord((prev) => undefined);
    setPasswordErrorWord((prev) => undefined);
    setisPasswordErrorWord((prev) => undefined);
    form.resetFields();
    setfocusItem(0);
    ele.current.style.transform = "";
  };
  useEffect(() => {
    // 初始化话得到的验证值都是undefined
  }, [form]);
  return (
    <Card style={{ width: 400 }} title="注 册" bordered={false} className="registForm">
      <Form onFinish={onFinish} form={form} hideRequiredMark>
        <Form.Item
          hasFeedback
          validateStatus={nameicon}
          help={<PromptBox info={nameerrorWord}></PromptBox>}
          labelCol={{ span: 3, pull: focusItem === 1 ? 1 : 0 }}
          wrapperCol={{ span: 20, pull: focusItem === 1 ? 1 : 0 }}
          name="username"
          label={
            <span
              className="iconfont icon-user"
              style={{ color: "#a8a5a7", fontSize: "20px", opacity: focusItem === 1 ? 1 : 0.6 }}
            ></span>
          }
          rules={[{ validator: checkName }]}
          colon={false}
        >
          <Input
            placeholder="用户名"
            onFocus={() => {
              setfocusItem(1);
            }}
            onBlur={() => {
              setfocusItem(0);
            }}
          />
        </Form.Item>
        <Form.Item
          name="password"
          hasFeedback
          validateStatus={passwordicon}
          help={<PromptBox info={passworderrorWord}></PromptBox>}
          labelCol={{ span: 3, pull: focusItem === 2 ? 1 : 0 }}
          wrapperCol={{ span: 20, pull: focusItem === 2 ? 1 : 0 }}
          colon={false}
          label={
            <span
              className="iconfont icon-lock"
              style={{ color: "#a8a5a7", fontSize: "20px", opacity: focusItem === 2 ? 1 : 0.6 }}
            ></span>
          }
          rules={[{ validator: checkPassword }]}
        >
          <Input.Password
            placeholder="密码"
            onFocus={() => {
              setfocusItem(2);
            }}
            onBlur={() => {
              setfocusItem(0);
            }}
          />
        </Form.Item>
        <Form.Item
          hasFeedback
          validateFirst
          help={<PromptBox info={isPassworderrWord}></PromptBox>}
          validateStatus={isPasswordicon}
          labelCol={{ span: 3, pull: focusItem === 3 ? 1 : 0 }}
          colon={false}
          wrapperCol={{ span: 20, pull: focusItem === 3 ? 1 : 0 }}
          label={
            <span
              className="iconfont icon-lock1"
              style={{ color: "#a8a5a7", fontSize: "20px", opacity: focusItem === 3 ? 1 : 0.6 }}
            ></span>
          }
          name="isPassword"
          rules={[{ validator: checkisPassword }]}
        >
          <Input.Password
            placeholder="确认密码"
            onFocus={() => {
              setfocusItem(3);
            }}
            onBlur={() => {
              setfocusItem(0);
            }}
          />
        </Form.Item>
        <Form.Item>
          <Space size={40}>
            <Button type="primary" shape="round" ghost onClick={submit}>
              注&nbsp;&nbsp;&nbsp;&nbsp;册
            </Button>

            <Button type="link" ghost onClick={toLogin}>
              登&nbsp;&nbsp;&nbsp;&nbsp;陆
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}
